package tester;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class FileTest {
	public static void main(String[] args) {

		String serviceURI = "http://www.zyd.com/BlogService";
		serviceURI = serviceURI.replaceAll("://", "/");
		serviceURI = serviceURI.replaceAll("\\\\", "/");
		serviceURI = serviceURI.replaceAll("\\.", "/");

		while (serviceURI.startsWith("/")) {
			serviceURI = serviceURI.substring(1);
		}
		while (serviceURI.endsWith("/")) {
			serviceURI = serviceURI.substring(0, serviceURI.length() - 1);
		}

		Boolean isFirstRound = true;
		String binString = "bin/service/";
		String srcString = "src/service/";
		// stubFilesDelete(binString + serviceURI, isFirstRound);
		// stubFilesDelete(srcString + serviceURI, isFirstRound);

		String sourcepath = "src/service/" + serviceURI;

		File[] files = new File(sourcepath).listFiles(new MyFilter());


		ArrayList<String> options = new ArrayList<String>();
		options.add("-sourcepath");
		options.add(sourcepath);
		options.add("-d");
		options.add("bin");
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(
				null, null, null);

		Iterable<? extends JavaFileObject> compilationUnits = fileManager
				.getJavaFileObjectsFromFiles(Arrays.asList(files));
		compiler.getTask(null, fileManager, null, options, null,
				compilationUnits).call();

	}

	static public void stubFilesDelete(String path, Boolean isFirstRound) {
		if (path.equals("bin/service") || path.equals("src/service")) {
			return;
		} else {
			File file = new File(path);
			if (file.exists()) {
				File[] files = file.listFiles();
				if (isFirstRound == true && files.length > 0) {
					for (File tempFile : files) {
						System.out.println(tempFile.getName());
						tempFile.delete();
					}
					System.out.println(file.getName());
					file.delete();
				} else if (files.length == 0) {
					System.out.println(file.getName());
					file.delete();
				}
				int lastIndex = path.lastIndexOf("/");
				if (lastIndex > 0) {
					path = path.substring(0, lastIndex);
				}
				stubFilesDelete(path, false);
			}
		}
	}

}

class MyFilter implements FilenameFilter {

	public boolean accept(File dir, String name) {
		// TODO: Add your code here
		return name.endsWith(".java");
	}

}
